package com.defysoft.waukids.diary;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity_UpPhoto;
import com.defysoft.waukids.Custom_Data_Type.WK_STUDENT;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.defysoft.waukids.gallery.Action;
import com.defysoft.waukids.gallery.CustomGallery;
import com.defysoft.waukids.notice.Notice_Write_Photo_View;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Diary_Main_Write extends BaseActivity_UpPhoto implements
		OnClickListener {
	boolean photo_up_check = false;
	ImageView iv_photo[] = new ImageView[10];
	ImageView iv_cancle[] = new ImageView[10];
	FrameLayout fl[] = new FrameLayout[10];
	TextView tv[] = new TextView[2];
	View v[] = new View[4];
	EditText et[] = new EditText[2];
	Toolbar toolbar;
	String stamp = "0";
	String stucode = "";
	private ImageLoader imageLoader;
	DisplayImageOptions defaultOptions;
	PublicSharedpreferences psf;
	Data_Sharedpreferences.SF_Member member;
	Data_Sharedpreferences.SF_School school;
	Sqlite_Connect sqlite_Connect;
	String photo = "";
	LinearLayout ly;
	private final int SUCCESS = 10;
	private final int FAIL = 9;
	private final int NETWORK_ERR = 8;
	private final int PHOTO_SUCCESS = 7;
	private final int GETLIST_SUCCESS = 6;
	ArrayList<CustomGallery> dataT;
	String[] all_path;

	int count;
	ArrayList<WK_STUDENT> stulist;
	ArrayList<Stu_List_Contents> select_list;
	Stu_List_Contents slc;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
			imageLoader.clearDiskCache();
			imageLoader.clearMemoryCache();

			all_path = data.getStringArrayExtra("all_path");
			dataT = new ArrayList<CustomGallery>();

			for (String string : all_path) {
				CustomGallery item = new CustomGallery();
				item.sdcardPath = string;
				dataT.add(item);
			}
			// 이미지뷰 초기화
			image_clear();

			for (int i = 0; i < dataT.size(); i++) {
				final int count = i;
				// 사진 셋팅
				image_setting(i);
				// 이미지 삭제 버튼
				iv_cancle[i].setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// 이미지뷰 초기화
						dataT.remove(count);
						image_clear();
						all_path = new String[dataT.size()];
						for (int j = 0; j < dataT.size(); j++) {
							all_path[j] = dataT.get(j).sdcardPath;
							image_setting(j);
						}
					}
				});
			}
		}
	}

	/** 내용 확인 */
	void check_Contents() {
		int check = 0;
		if (et[0].getText().toString().length() < 2) {
			Toast.makeText(this, "제목을 2글자 이상으로 입력해주세요", Toast.LENGTH_SHORT)
					.show();
			check = 1;
		}
		if (et[1].getText().toString().length() < 2) {
			Toast.makeText(this, "내용을 2글자 이상으로 입력해주세요.", Toast.LENGTH_SHORT)
					.show();
			check = 1;
		}
		if (stucode.equals("")) {
			Toast.makeText(this, "원아를 선택해주세요.", Toast.LENGTH_SHORT).show();
			check = 1;
		}
		if (check == 0) {

			if (dataT.size() == 0) {
				startNetwork(1);
			} else {
				upImageThread(0);
			}
		}
	}

	/** 이미지뷰 초기화 */
	void image_clear() {
		if (dataT.size() == 0) {
			ly.setVisibility(View.GONE);
			tv[1].setVisibility(View.VISIBLE);
		} else {
			tv[1].setVisibility(View.GONE);
			ly.setVisibility(View.VISIBLE);
		}
		for (int i = 0; i < 10; i++) {
			fl[i].setVisibility(View.GONE);
			iv_cancle[i].setVisibility(View.GONE);
			iv_photo[i].setVisibility(View.GONE);
			iv_photo[i].setImageResource(0xff37b34a);
		}
	}

	/** 이미지뷰 셋팅 */
	void image_setting(int i) {
		final int count = i;
		fl[i].setVisibility(View.VISIBLE);
		iv_photo[i].setScaleType(ScaleType.FIT_XY);
		iv_photo[i].setVisibility(View.VISIBLE);
		iv_cancle[i].setVisibility(View.VISIBLE);
		if (i == 9) {

		} else {
			fl[i + 1].setVisibility(View.VISIBLE);
			iv_photo[i + 1].setVisibility(View.VISIBLE);
			iv_cancle[i + 1].setVisibility(View.GONE);
			iv_photo[i + 1].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
					i.putExtra("path", all_path);
					startActivityForResult(i, 200);
				}
			});
		}

		imageLoader.displayImage("file://" + dataT.get(i).sdcardPath,
				iv_photo[i], defaultOptions);
		// 이미지 클릭시
		iv_photo[i].setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Diary_Main_Write.this,
						Notice_Write_Photo_View.class);
				intent.putExtra("path", all_path);
				intent.putExtra("count", count + "");
				startActivity(intent);
			}
		});
	}

	private void setStartToolbar() {
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.diary_main_write);
		photo_ImageContainer();
		setStartData();
		setStartToolbar();
		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
	}

	@Override
	public void setStartData() {
		super.setStartData();
		sqlite_Connect = new Sqlite_Connect(this);
		photo_ImageContainer();
		Init();
		dataT = new ArrayList<CustomGallery>();
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		psf.setSchoolsp();
		school = psf.getSchoolsp();
		member = psf.getMembersp();
		toolbar = (Toolbar) findViewById(R.id.DIARY_MAIN_WRITE_TOOLBAR);
		et[0] = (EditText) findViewById(R.id.DIARY_MAIN_TITLE);
		et[1] = (EditText) findViewById(R.id.DIARY_MAIN_SUB);
		v[0] = (View) findViewById(R.id.DIARY_MAIN_STAMP_1);
		v[1] = (View) findViewById(R.id.DIARY_MAIN_STAMP_2);
		v[2] = (View) findViewById(R.id.DIARY_MAIN_STAMP_3);
		v[3] = (View) findViewById(R.id.DIARY_WRITE_TOOLBAR_SAVE);
		tv[0] = (TextView) findViewById(R.id.DIARY_MAIN_STUDENT);
		tv[1] = (TextView) findViewById(R.id.DIARY_MAIN_PHOTO_UP);
		for (int i = 0; i < v.length; i++) {
			v[i].setOnClickListener(this);
		}
		tv[0].setOnClickListener(this);
		tv[1].setOnClickListener(this);

	}

	/** 원생 리스트 받아오는 Thread */
	void stulistThread() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_DIARY_MAIN_STULIST + "&FK_Sch_Stu_Code="
							+ member.School + "&FK_Cla_Stu_Code="
							+ member.Class));

			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(GETLIST_SUCCESS,
						jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR,e.toString()+" where stulistThread()");
		}
	}

	/** 글올리는 Thread */
	void mainThread() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_DIARY_MAIN_WRITE + "&PK_Mem_Email="
							+ member.Email + "&FK_Sch_Dia_Code="
							+ member.School + "&FK_Stu_Dia_Code=" + stucode
							+ "&FK_Cla_Dia_Code=" + member.Class + "&subject="
							+ et[1].getText().toString() + "&title="
							+ et[0].getText().toString() + "&stamp=" + stamp
							+ "&photo=" + photo));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS, jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR,e.toString()+" where mainThread()");
		}
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {

			@Override
			public void run() {
				switch (cho) {
				case 0:
					stulistThread();

					break;

				case 1:
					mainThread();
					break;
				}
			}
		});
		firstThread.start();
		if (choice == 0) {
			startDIal();
		}
		if (dataT.size() == 0) {
			startDIal();
		}
	}

	@Override
	public void upImageThread(int choice) {
		super.upImageThread(choice);
		final int cho = choice;
		upThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				for (int i = 0; i < dataT.size(); i++) {

					JSONObject jsonObject = null;
					try {
						StringBuffer postDataBuilder = new StringBuffer();
						// 추가하고 싶은 Key & Value 추가key & value를 추가한 후 꼭 경계선을 삽입해줘야
						// 데이터를 구분할 수 있다.파일 첨부
						postDataBuilder.append(delimiter);
						postDataBuilder.append(setValue("filename", "diary"));
						postDataBuilder.append(delimiter);
						postDataBuilder
								.append(setValue("folder", "diaryphoto"));
						postDataBuilder.append(delimiter);
						postDataBuilder.append(setFile("photo", "temp.jpg"));
						postDataBuilder.append("\r\n");
						// 커넥션 생성 및 설정
						HttpURLConnection conn = (HttpURLConnection) new URL(
								HTTP_URL_PHOTOUP).openConnection();
						conn.setDoInput(true);
						conn.setDoOutput(true);
						conn.setUseCaches(false);
						conn.setRequestMethod("POST");
						conn.setRequestProperty("Connection", "Keep-Alive");
						conn.setRequestProperty("Content-Type",
								"multipart/form-data;boundary=" + boundary);// 전송
																			// 작업
																			// 시작

						DataOutputStream out = new DataOutputStream(
								new BufferedOutputStream(conn.getOutputStream()));
						// 위에서 작성한 메타데이터를 먼저 전송한다. (한글이 포함되어 있으므로 UTF-8 메소드사용)
						out.writeUTF(postDataBuilder.toString());

						// 사진 리사이징 && 사진 방향 지정 코드
						byte[] buffer = resizeBitmap(Diary_Main_Write.this,
								dataT.get(i).sdcardPath);

						// 버퍼 크기만큼 파일로부터 바이트 데이터를 읽는다.전송
						out.write(buffer);
						out.writeBytes(delimiter); // 반드시 작성해야 한다.
						out.flush();
						out.close();

						// 전송끝, 피드백
						BufferedReader br = new BufferedReader(
								new InputStreamReader(conn.getInputStream()));
						String checkmsg;
						String msg = br.readLine();
						while ((checkmsg = br.readLine()) != null) {
							msg += checkmsg;
						}
						jsonObject = new JSONObject(msg);
						if (jsonObject.getString("success").equals("true")) {
							// 성공처리
							if (photo.equals("")) {
								photo = jsonObject.getString("payload");
							} else {
								photo += "|" + jsonObject.getString("payload");
							}
							photo_up_check = true;
						} else {
							onNetworkCallback(FAIL,
									jsonObject.getString("message"));
							photo_up_check = false;
						}
					} catch (Exception e) {
						onNetworkCallback(NETWORK_ERR,e.toString()+" where upImageThread()");
						photo_up_check = false;
					}
				}
				if (photo_up_check == true) {
					onNetworkCallback(PHOTO_SUCCESS, "");
				}
			}
		});
		upThread.start();

		startDIal();

	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);

		switch (_message.what) {
		case GETLIST_SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			stulist = JsonParser.Student_List((String) _message.obj);
			stulist_alert();
			break;

		case SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			setResult(REFRESH_CODE);
			finish();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			endDIal();

			break;

		case PHOTO_SUCCESS:
			if (upThread != null) {
				upThread.interrupt();
			}
			startNetwork(1);
			break;

		case FAIL:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;

		case NETWORK_ERR:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Diary_Main_Write", member.Email);
			break;
		}

	}

	// 이미지 로더 옵션
	void Init() {
		defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisk(true).imageScaleType(ImageScaleType.EXACTLY)
				.considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
				.build();

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
				.memoryCacheSize(2 * 1024 * 1024).memoryCacheSizePercentage(20)
				.diskCacheSize(50 * 1024 * 1024).diskCacheFileCount(100)
				.diskCacheExtraOptions(480, 320, null)
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(config);
	}

	/** 이미지 셋팅 */
	void photo_ImageContainer() {
		ly = (LinearLayout) findViewById(R.id.DIARY_MAIN_PHOTO_CONTAINER);
		iv_photo[0] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_1);
		iv_photo[1] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_2);
		iv_photo[2] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_3);
		iv_photo[3] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_4);
		iv_photo[4] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_5);
		iv_photo[5] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_6);
		iv_photo[6] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_7);
		iv_photo[7] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_8);
		iv_photo[8] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_9);
		iv_photo[9] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_10);

		iv_cancle[0] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_CANCLE_1);
		iv_cancle[1] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_CANCLE_2);
		iv_cancle[2] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_CANCLE_3);
		iv_cancle[3] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_CANCLE_4);
		iv_cancle[4] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_CANCLE_5);
		iv_cancle[5] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_CANCLE_6);
		iv_cancle[6] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_CANCLE_7);
		iv_cancle[7] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_CANCLE_8);
		iv_cancle[8] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_CANCLE_9);
		iv_cancle[9] = (ImageView) findViewById(R.id.DIARY_MAIN_PHOTO_CANCLE_10);

		fl[0] = (FrameLayout) findViewById(R.id.DIARY_MAIN_PHOTO_FRAME_1);
		fl[1] = (FrameLayout) findViewById(R.id.DIARY_MAIN_PHOTO_FRAME_2);
		fl[2] = (FrameLayout) findViewById(R.id.DIARY_MAIN_PHOTO_FRAME_3);
		fl[3] = (FrameLayout) findViewById(R.id.DIARY_MAIN_PHOTO_FRAME_4);
		fl[4] = (FrameLayout) findViewById(R.id.DIARY_MAIN_PHOTO_FRAME_5);
		fl[5] = (FrameLayout) findViewById(R.id.DIARY_MAIN_PHOTO_FRAME_6);
		fl[6] = (FrameLayout) findViewById(R.id.DIARY_MAIN_PHOTO_FRAME_7);
		fl[7] = (FrameLayout) findViewById(R.id.DIARY_MAIN_PHOTO_FRAME_8);
		fl[8] = (FrameLayout) findViewById(R.id.DIARY_MAIN_PHOTO_FRAME_9);
		fl[9] = (FrameLayout) findViewById(R.id.DIARY_MAIN_PHOTO_FRAME_10);
	}

	/** 네.아니오.선택다이얼로그 */
	void alertDialog() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog alert;
		builder.setMessage("원아수첩을 등록 하시겠습니까?")
				.setCancelable(false)
				.setPositiveButton("네", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						check_Contents();
					}
				})
				.setNegativeButton("아니오",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		alert = builder.create();
		alert.show();
	}

	/** 원생 리스트 alertDialog */
	void stulist_alert() {
		select_list = new ArrayList<Stu_List_Contents>();

		Stulist_Adapter stulist_adapter = new Stulist_Adapter();
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(
				Diary_Main_Write.this);
		LayoutInflater inflater = getLayoutInflater();
		View convertView = (View) inflater.inflate(
				R.layout.diary_alert_listview, null);
		alertDialog.setView(convertView);
		alertDialog.setTitle("원생 리스트");
		alertDialog.setCancelable(false)
				.setNegativeButton("취소", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				})
				.setPositiveButton("확인", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String name = "";

						if (select_list.size() != 0) {
							for (int i = 0; i < select_list.size(); i++) {
								if (i == 0) {
									stucode = select_list.get(i).pk_stu_code;
									name = select_list.get(i).stu_name;
								} else {
									name += "/" + select_list.get(i).stu_name;
									stucode += "|"
											+ select_list.get(i).pk_stu_code;
								}
							}
							tv[0].setText(name);
						}
					}
				});
		final ListView lv = (ListView) convertView
				.findViewById(R.id.DIARY_ALERT_LISTVIEW);
		lv.setAdapter(stulist_adapter);
		alertDialog.show();

		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (select_list.size() == 0) {
					slc = new Stu_List_Contents(
							stulist.get(position).PK_Stu_Code, stulist
									.get(position).Stu_Name);
					select_list.add(slc);
					((LinearLayout) view
							.findViewById(R.id.DIARY_ALERT_LIST_ROW))
							.setBackgroundColor(0xff37b34a);
				} else {
					boolean checked = true;

					for (int i = 0; i < select_list.size(); i++) {
						if (select_list.get(i).pk_stu_code.equals(stulist
								.get(position).PK_Stu_Code)) {
							checked = false;
							select_list.remove(i);
							break;
						}
					}
					if (checked) {
						slc = new Stu_List_Contents(
								stulist.get(position).PK_Stu_Code, stulist
										.get(position).Stu_Name);
						select_list.add(slc);
						((LinearLayout) view
								.findViewById(R.id.DIARY_ALERT_LIST_ROW))
								.setBackgroundColor(0xff37b34a);
					} else {
						((LinearLayout) view
								.findViewById(R.id.DIARY_ALERT_LIST_ROW))
								.setBackgroundColor(0xffffffff);
					}

				}

			}
		});
	}

	/** 원생 리스트 정보 */
	class Stu_List_Contents {
		String pk_stu_code = "";
		String stu_name = "";

		public Stu_List_Contents(String pk, String stu) {
			this.pk_stu_code = pk;
			this.stu_name = stu;
		}
	}

	/** 원생 리스트 Adapter */
	class Stulist_Adapter extends ArrayAdapter<String> {

		public Stulist_Adapter() {
			super(Diary_Main_Write.this, android.R.layout.simple_list_item_1);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			return stulist.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.diary_alert_list_row, null);
				holder.stu_iv = (ImageView) convertView
						.findViewById(R.id.DIARY_ALERT_LIST_IMAGE);
				holder.stu_tv = (TextView) convertView
						.findViewById(R.id.DIARY_ALERT_LIST_NAME);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.stu_tv.setText(stulist.get(position).Stu_Name);
			holder.stu_iv.setImageResource(0x00ffffff);
			imageLoader.displayImage(
					HTTP_URL_STUDENTPHOTO + stulist.get(position).Stu_Photo,
					holder.stu_iv);

			return convertView;
		}

		class ViewHolder {
			TextView stu_tv;
			ImageView stu_iv;
		}
	}

	/** 클릭 이벤트 */
	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.DIARY_MAIN_PHOTO_UP:
			Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
			i.putExtra("path", all_path);
			startActivityForResult(i, 200);
			break;
		case R.id.DIARY_MAIN_STUDENT:
			startNetwork(0);
			break;
		case R.id.DIARY_WRITE_TOOLBAR_SAVE:
			alertDialog();

			break;
		case R.id.DIARY_MAIN_STAMP_1:
			if (stamp.equals("1")) {
				this.v[0].setBackgroundResource(R.drawable.stamp_one);
				stamp = "0";
			} else {
				this.v[1].setBackgroundResource(R.drawable.stamp_two);
				this.v[2].setBackgroundResource(R.drawable.stamp_three);
				this.v[0].setBackgroundResource(R.drawable.stamp_one_fill);
				stamp = "1";
			}

			break;
		case R.id.DIARY_MAIN_STAMP_2:
			if (stamp.equals("2")) {
				this.v[1].setBackgroundResource(R.drawable.stamp_two);
				stamp = "0";
			} else {
				this.v[0].setBackgroundResource(R.drawable.stamp_one);
				this.v[2].setBackgroundResource(R.drawable.stamp_three);
				this.v[1].setBackgroundResource(R.drawable.stamp_two_fill);
				stamp = "2";
			}
			break;
		case R.id.DIARY_MAIN_STAMP_3:
			if (stamp.equals("3")) {
				this.v[2].setBackgroundResource(R.drawable.stamp_three);
				stamp = "0";
			} else {
				this.v[0].setBackgroundResource(R.drawable.stamp_one);
				this.v[1].setBackgroundResource(R.drawable.stamp_two);
				this.v[2].setBackgroundResource(R.drawable.stamp_three_fill);

				stamp = "3";
			}
			break;
		}
	}

	private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(
					R.layout.toast_layout, null);
			TextView toast_tv = (TextView) layout
					.findViewById(R.id.TOAST_LAYOUT_TV);
			Toast toast = new Toast(Diary_Main_Write.this);
			toast.setView(layout);
			toast_tv.setText(intent.getStringExtra("PUSH_NAME") + " : "
					+ intent.getStringExtra("PUSH_SUB"));
			toast.setDuration(Toast.LENGTH_LONG);
			toast.show();
		}
	};

}
